<?php
namespace app\service;

use app\model\RoomModel;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

/**
 * @author wanQQ
 */
class RoomService extends BaseService
{
    protected RoomModel $roomModel;
    protected function initialize() {
        parent::initialize();
        $this->roomModel = new RoomModel();
    }

    /**
     * 获取房间号列表(数组)
     * @return Collection|array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getRoomIdList(): Collection|array
    {
        $roomList = $this->roomModel->field("id as value,room_name as label")->select();
        return $roomList;
    }

    /**
     * 插入房间号
     * @param $info
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function insertRoom($info): mixed
    {
        $roomInfo = $this->roomModel->where("room_id","=",$info["room_id"])->field("id")->find();
        if(!$roomInfo) {
            $data = [
                "room_id" => (int)$info["room_id"],
                "room_name" => $info["room_name"],
                "create_time" => date("Y-m-d H:i:s"),
                "update_time" => date("Y-m-d H:i:s")
            ];
            try {
                $roomId = $this->roomModel->insertGetId($data);
            }catch (\Exception $e){
                Log::error(date("Y-m-d H:i:s")."存入新房间失败  ".json_encode($info,JSON_UNESCAPED_UNICODE)."  详情:" . $e->getMessage());
                exit();
            }
        }else {
            $roomId = $roomInfo->id;
        }
        return $roomId;
    }
}